package com.eightbears.beboy.ui.merchant.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ReserveListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.ReserveEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SUBMIT_BOOKS;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.entity.ReserveEntity.STATUS_AGREE;
import static com.eightbears.beboy.entity.ReserveEntity.STATUS_REFUSE;
import static com.eightbears.beboy.ui.merchant.activity.ShopRefuseActivity.EVENT_REFUSE;

public class ShopReservesActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    public static final String PARAMS_RESERVE_INFO = "reserveInfo";

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private UserEntity.Shop shop;
    private ReserveEntity.ReserveInfo reserveInfo;
    private ReserveListAdapter reserveListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_reserves);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();

    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        shop = SPUtil.getUser().getData().getShops().get(0);
        tv_title.setText(R.string.text_shop_reserve);
        initAdapter();
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        reserveListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                reserveInfo = (ReserveEntity.ReserveInfo) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.tv_ok:
                        executeReserve();
                        break;
                    case R.id.tv_cancel:
                        startLocalActivity(ShopReservesActivity.this, ShopRefuseActivity.class,
                                PARAMS_RESERVE_INFO, reserveInfo);
                        break;
                    case R.id.tv_call:
                        call(reserveInfo.getMobile());
                        break;
                }
            }
        });

        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back) void back(){
        finish();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(mContext));
        reserveListAdapter = new ReserveListAdapter();
        reserveListAdapter.openLoadAnimation();
        reserveListAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(reserveListAdapter);
    }

    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_SUBMIT_BOOKS)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("type", "2")
                .addParams("shop_id", shop.getShop_id())
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                ReserveEntity reserveEntity = GsonUtil.fromJson(response, ReserveEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(reserveEntity.getStatus_code())) {
                    isEnd = reserveEntity.getData().getIs_end();
                    if (page == 1) {
                        reserveListAdapter.setNewData(reserveEntity.getData().getList());
                        if (reserveEntity.getData().getList().size() == 0)
                            view_empty.setVisibility(View.VISIBLE);
                        else
                            view_empty.setVisibility(View.GONE);
                    } else {
                        reserveListAdapter.addData(reserveEntity.getData().getList());
                        reserveListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopReservesActivity.this, status_error);
            }
        });
    }

    /**
     * 预订确认
     */
    private void executeReserve() {
        swipeLayout.setRefreshing(true);
        String url = URL_SUBMIT_BOOKS + "/" + reserveInfo.getId();
        OkHttpUtils.put().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("status", STATUS_AGREE)
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                reserveInfo.setStatus(STATUS_AGREE);
                reserveListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopReservesActivity.this, status_error);
            }
        });
    }

    /**
     * 调用拨号界面
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        reserveListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                reserveListAdapter.getData().clear();
                getData();
                reserveListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    reserveListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(mContext, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        reserveListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_REFUSE:
                reserveInfo.setStatus(STATUS_REFUSE);
                reserveListAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
